/**
 * Created by dimy1 on 2015/12/30.
 */
//This is for the wechat access
var http=require('http'),
    url=require('url'),
    querystring=require('querystring'),
    crypto=require('crypto');
var sha1=crypto.createHash('sha1');
var TOKEN='dimy';
http.createServer(function(req,res){
    res.writeHead(200,{'Content-type':'text/plain'});
    var pathname=url.parse(req.url).pathname;
    var paramStr=url.parse(req.url).query;
    var param=querystring.parse(paramStr);
    if(pathname=='/favicon.ico'){
        return;
    }
    //console.log(param['name']);
    res.end(valid(param['echostr'],param['signature'],param['timestamp'],param['nonce']));
}).listen(9000,"localhost");

function valid(echostr,signature,timestamp,nonce){
    if(checkSignature(signature,timestamp,nonce)){
        return echostr;
    }else{
        return 'error';
    }
}
function checkSignature(signature,timestamp,nonce){
    var token=TOKEN;
    var tmpArr=[token,timestamp,nonce];
    tmpArr=tmpArr.sort();
    var tmpStr=tmpArr.join('');
    sha1.update(tmpStr);
    tmpStr=sha1.digest('hex');
    if(tmpStr==signature){
        return true;
    }else{
        return false;
    }

}


